const app = getApp();
const { URL } = require('./api.js');
export function blueToothPay(_this) {
  // let _this = owner;
  _this.bind = function () {
    _this.TestOpenBluetooth().then(res => {
      setTimeout(() => {
        wx.getBluetoothAdapterState({   // 获取本机的蓝牙状态
          success: function (res) {
            _this.startBluetoothDevicesDiscovery();      // 搜素蓝牙
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }, 1000)
    })
  };
  /**
   *检测蓝牙是否开启
   */
  _this.TestOpenBluetooth = function () {
    return new Promise((resolve, reject) => {
      if (wx.openBluetoothAdapter) {
        wx.openBluetoothAdapter({
          success: function (res) {
            resolve(res)
          },
          fail: function (res) {
            wx.showModal({
              content: '请开启手机蓝牙后再试'
            })
            _this.setData({
              status: 2
            })
          }
        })
      }

    })
  };
  // 搜素蓝牙
  _this.startBluetoothDevicesDiscovery = function () {
    setTimeout(() => {
      wx.startBluetoothDevicesDiscovery({  //搜素蓝牙
        success: function (res) {
          console.log('开始搜索到设备');
          _this.getDevices();// 发现设备
        }
      });
    }, 1000);
  },
    /**
     *发现可选择的蓝牙设备并匹配对应的机器
     */
    _this.getDevices = function () {
      wx.showLoading({
        title: '正在搜索设备',
      })
      setTimeout(() => {
        wx.getBluetoothDevices({
          allowDuplicatesKey: false,
          interval: 0,
          success: function (res) {
            wx.hideLoading();
            if (res.devices.length > 0) {
              let boolean = false;  // 判断是否存在需要搜索的设备
              for (let i = 0; i < res.devices.length; i++) {
                //判断是否存在需要搜索的设备
                if (res.devices[i].name == app.globalData.terminalCode || res.devices[i].localName == app.globalData.terminalCode) {
                   boolean = true;
                }
              }
              // 有此设备的存在
              if(boolean){
                for (let i = 0; i < res.devices.length; i++) {
                  console.log(res.devices[i])
                  //检索指定设备
                  if (res.devices[i].name == app.globalData.terminalCode || res.devices[i].localName == app.globalData.terminalCode) {
                    _this.setData({
                      deviceId: res.devices[i].deviceId
                    })
                    console.log('已找到指定设备:', res.devices[i].deviceId);
                    _this.createBLEConnection();//连接设备
                  }
                }
              }
              // 没有搜索到指定设备,表示失败
              else{
                _this.setData({
                  status: 2,
                  count: ++_this.data.count
                })
                wx.closeBluetoothAdapter({  // 关闭蓝牙模块
                  success(res) {
                    console.log(res)
                  }
                })
              }
            }
            else {
              _this.setData({
                status: 2,
                count: ++_this.data.count
              })
              wx.closeBluetoothAdapter({  // 关闭蓝牙模块
                success(res) {
                  console.log(res)
                }
              })
            }

          },
          fail() {}
        })
      }, 1000)

    };

  /**
   * 在搜索到设备后通过拿到的设备的deviceId去连接设备,然后去获取所连接蓝牙设备的service服务
   */
  _this.createBLEConnection = function () {
    wx.createBLEConnection({
      deviceId: _this.data.deviceId,//搜索设备获得的蓝牙设备 id
      success: function (res) {
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log(res, '停止搜索')
          }
        })
        _this.getBLEDeviceServices();//连接成功以后就可以去获取设备的服务列表,获取指定的的服务ID
      },
      fail: function (res) {
        console.log("连接失败");
        _this.setData({
          status: 2,
          count: ++_this.data.count
        })
        console.log(_this.data.count)
        wx.closeBluetoothAdapter({  // 关闭蓝牙模块
          success(res) {
            console.log(res)
          }
        })
      }
    })
  };
  /**
   * 连接成功以后就可以去获取设备的服务列表,获取指定的的服务ID
   */
  _this.getBLEDeviceServices = function () {
    setTimeout(() => {
      wx.getBLEDeviceServices({
        deviceId: _this.data.deviceId,//搜索设备获得的服务 id
        success: function (res) {
          console.log(res)
          _this.setData({
            service_id: res.services[0].uuid
          })
          _this.getBLEDeviceCharacteristics();//获取特征值
        },
        fail(res) {
          console.log(res);
        }
      });
    }, 2000)

  };
  /**
   * 获取特征值,需要的是能读，能写，能监听的那个值的uuid作为特征值id
   */
  _this.getBLEDeviceCharacteristics = function () {
    let that = this;
    setTimeout(() => {
      wx.getBLEDeviceCharacteristics({
        deviceId: _this.data.deviceId,//搜索设备获得的蓝牙设备 id
        serviceId: _this.data.service_id,//服务ID
        success: function (res) {
          console.log('device特征值:', res.characteristics)
          for (let i = 0; i < res.characteristics.length; i++) {
            let item = res.characteristics[i]
            if (item.properties.notify) {
              _this.setData({
                indicate_id: item.uuid //用来通知的值
              })
              console.log(_this.data.indicate_id)
            }
            if (item.properties.write) {
              _this.setData({
                write_id: item.uuid//用来写入的值
              })
              console.log(_this.data.write_id)
              console.log(app.globalData.message)
              _this.hexStringToArrayBuffer(app.globalData.message)  // 转换成ArrayBuffer, 写入蓝牙数据，先调用这个方法
            }
          }
        }
      });
    }, 1000)

  };

  /**
   * 开启notify
   */
  _this.openNotify = function () {
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: _this.data.deviceId,//蓝牙设备id
      serviceId: _this.data.service_id,//服务id
      characteristicId: _this.data.indicate_id,//1.开启监听 notityid  2. 发送指令 write
      success: function (res) {
        console.log('开启notify')
        //监听低功耗蓝牙设备的特征值变化
        wx.onBLECharacteristicValueChange((res)=>{
          // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,通过方法转换成字符串
          console.log(res + "蓝牙测试返回的数据" + res.value);
          if (res.value) {    // 如果接收到有数据
            app._get(URL.orderPaid + app.globalData.orderCode, {}, res => {
              _this.setData({
                status: 1
              })
              wx.closeBluetoothAdapter({  // 数据是否接受成功,关闭蓝牙模块
                success(res) {
                  console.log(res)
                }
              })
            })
          }
        });
      },
      fail: function (err) {
        console.log('openNotify err: ', err)
      }
    });
  };
  /**
   * 写入数据
   */
  _this.writeIntoBELEDevice = function (sendloop,i) {
    console.log(sendloop)
    if (i >= sendloop.length) {
        _this.openNotify(); // 数据写入完成后开启监听
        return;   // 当传送的字节数组大于拆分后的数组长度，不写入数据
    }
    let hexArray = new Uint8Array(sendloop[i].match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    }))
    console.log(hexArray.buffer)    
    wx.writeBLECharacteristicValue({
      deviceId: _this.data.deviceId,//设备deviceId
      serviceId: _this.data.service_id,//设备service_id
      characteristicId: _this.data.write_id,//设备write特征值
      value: hexArray.buffer,//写入数据
      success: function (res) {
        console.log(`第${i}写入成功`);
        setTimeout(() => {
          _this.writeIntoBELEDevice(sendloop, i + 1);
        }, 1001); // 分包发送需要隔断时间发送
      },
      fail: function (res) {
        console.log(res);
        console.log("写入失败")
        _this.setData({
          status: 2,
          count: ++_this.data.count
        })
        console.log(_this.data.count)
        wx.closeBluetoothAdapter({  // 关闭蓝牙模块
          success(res) {
            console.log(res)
          }
        })
      },
      complete: function () {
        console.log("调用结束");

      }
    });
  };
  /**
   * 拆分数组方法，分包情况下,每20个字节作为一个发送包
   */
  _this.split_array = function (arr, len) {
    let a_len = arr.length
    let result = []
    for (var i = 0; i < a_len; i += len) {
      result.push(arr.slice(i, i + len))
    }
    console.log(result)
    return result;
  };

  /**
   * 转化为ArrayBuffer
   */
  _this.hexStringToArrayBuffer = function (str) {
    if (!str) {
      return new ArrayBuffer(0);
    }
    // 拆分数组 每40个元素组成一个新数组,40个元素为20个字节
    let sendloop = _this.split_array(str, 40);
    setTimeout(() => {
      _this.writeIntoBELEDevice(sendloop, 0);
    }, 2000) // 首次写入蓝牙数据包
  };

  /**
   * ArrayBuffer转16进制字符串
   */
  _this.ab2hext = function (buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    );
    return hexArr.join('');
  };
  _this.bind();
}